package com.lzz.bottomencapsulation.net;

import android.content.Context;
import android.text.TextUtils;

import com.lzz.bottomencapsulation.consts.NetConsts;
import com.lzz.bottomencapsulation.utils.NetUtils;
import com.lzz.bottomencapsulation.utils.TUtils;

import rx.Subscriber;

public class SubscriberOne<D, R extends RequestCallBack<D>> extends Subscriber<HttpRequestData<D>> {
    R r;
    Context context;

    public SubscriberOne(R r, Context context) {
        this.r = r;
        this.context = context;
    }

    @Override
    public void onStart() {
        super.onStart();
        r.onStart();
    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        r.onStop();
        if (!NetUtils.isConnected(context)) {
            TUtils.showShort(context, "网络未连接，请检查网络");
            r.networkNotConnected();
            return;
        }
        r.onRequestfail(NetConsts.NETWORK_REQUEST_METHOD_ERROR, "请求服务器出错，请稍后重试");

    }

    @Override
    public void onNext(HttpRequestData<D> tHttpRequestData) {
        r.onStop();
        if (tHttpRequestData == null || TextUtils.isEmpty(tHttpRequestData.getErrno())) {
            r.onRequestfail(NetConsts.NETWORK_REQUEST_METHOD_REQUESTDATANUll, "请求服务器出错,无返回值");
            return;
        }
        switch (tHttpRequestData.getErrno()) {
            case NetConsts.ERROR_CODE_0:
                r.onRequestSuccess(tHttpRequestData.getData());
                break;
            default:
                TUtils.showShort(context, tHttpRequestData.getErrmsg());
                r.onRequestfail(Integer.parseInt(tHttpRequestData.getErrno()), tHttpRequestData
                        .getErrmsg());
                break;
        }
    }
}

